package com.yunquan.ohana.ui.calendar.event.month

import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.binding.command.BindingAction
import com.yunquan.ohana.base.binding.command.BindingCommand
import com.yunquan.ohana.base.bus.RxBus
import com.yunquan.ohana.base.ui.ItemViewModel
import com.yunquan.ohana.entity.EventEntity
import com.yunquan.ohana.entity.EventType
import com.yunquan.ohana.ui.calendar.event.month.adapter.EventMonthChildAdapter
import com.yunquan.ohana.utils.DateUtils
import com.yunquan.ohana.utils.Utils
import me.tatarka.bindingcollectionadapter2.ItemBinding
import java.time.LocalDate
import java.time.LocalDateTime

class EventMonthItemViewModel(viewModel: EventMonthViewModel) : ItemViewModel<EventMonthViewModel>(viewModel) {

    var date: String? = null
    val adapter = EventMonthChildAdapter()
    val items = ObservableArrayList<EventMonthChildItemViewModel>()
    val itemBinding = ItemBinding.of<EventMonthChildItemViewModel>(
        BR.eventMonthChildItemViewModel,
        R.layout.item_event_month,
    )
    val isShowMore = ObservableField<Boolean>()
    val count = ObservableField<String>()
    val day = ObservableField<String>()
    val color = ObservableField<Int>()
    val textColor = ObservableField<Int>()

    constructor(
        viewModel: EventMonthViewModel,
        date: String,
        currentDateTime: LocalDateTime,
        child: List<EventMonthChildItemViewModel>,
    ) : this(viewModel) {
        this.date = date
        setData(currentDateTime, child)
    }

    fun setData(currentDateTime: LocalDateTime, child: List<EventMonthChildItemViewModel>) {
        this.items.clear()
        this.items.addAll(child)
        this.count.set("${items.size} ${Utils.instance.getString(R.string.more)}")
        this.isShowMore.set(items.isNotEmpty())
        LocalDate.parse(date).let {
            day.set(it.dayOfMonth.toString())
            color.set(
                if (it == LocalDate.now()) {
                    textColor.set(Utils.instance.context.getColor(R.color.white))
                    Utils.instance.context.getColor(R.color.c_FF9932)
                } else if (it.monthValue == currentDateTime.monthValue) {
                    textColor.set(Utils.instance.context.getColor(R.color.c_20))
                    Utils.instance.context.getColor(R.color.white)
                } else {
                    textColor.set(Utils.instance.context.getColor(R.color.c_C3C3C3))
                    Utils.instance.context.getColor(R.color.white)
                }
            )
        }
    }

    val onItemClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            RxBus.getDefault().post(EventEntity(EventType.EVENT_GO_SHOW_WEEK, date))
        }
    })
}